package com.star.security.filter;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限拦截器
 *
 * @author yangzj
 */
public class AccessInterceptor implements HandlerInterceptor {

    private final AccessChecker accessChecker;
    public AccessInterceptor(AccessChecker accessChecker) {
        this.accessChecker = accessChecker;
    }

    @SuppressWarnings("NullableProblems")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            // 无需权限校验。ErrorController 是 Spring Boot 提供的默认错误处理器之一，用于处理应用程序中的错误情况并返回适当的错误响应
            if (ErrorController.class.isAssignableFrom(((HandlerMethod) handler).getBean().getClass())) {
                return true;
            }
            return accessChecker.check((HandlerMethod) handler);
        }
        return true;
    }
}
